package com.mo.lib.utils

import android.os.SystemClock
import android.view.View
import java.util.concurrent.TimeUnit

/**
 * @ author：mo
 * @ data：2022/3/28:10:40
 * @ 功能：
 */
/**
 * 点击事件防抖动
 * @param interval 间隔时间, 如果为1000表示1000毫秒内只允许触发一次点击事件
 * @param unit 时间单位
 */
/** 间隔时间常量    */
const val CLICK_INTERVAL_TIME = 600L


fun View.setClick(interval: Long = CLICK_INTERVAL_TIME, unit: TimeUnit = TimeUnit.MILLISECONDS, block: View.() -> Unit):View {
    setOnClickListener(ThrottleClickListener(interval, unit, block))
    return this
}
fun View.setClick(interval: Long = CLICK_INTERVAL_TIME,  block: View.() -> Unit)=setClick(interval, TimeUnit.MILLISECONDS,block)

/** 防止重复点击==》》锁view*/
fun View.setClickLock(interval: Long = CLICK_INTERVAL_TIME, unit: TimeUnit = TimeUnit.MILLISECONDS, block: View.() -> Unit) {
    isClickable = false
    setOnClickListener {
        block.invoke(it)
    }
    this.postDelayed({ isClickable = true }, unit.toMillis(interval))
}

internal class ThrottleClickListener(private val interval: Long = CLICK_INTERVAL_TIME, private val unit: TimeUnit = TimeUnit.MILLISECONDS, private var block: View.() -> Unit) : View.OnClickListener {
    private var lastTime: Long = 0
    override fun onClick(v: View) {
        val currentTime = SystemClock.elapsedRealtime()
        if (currentTime - lastTime > unit.toMillis(interval)) {
            lastTime = currentTime
            block(v)
        }
    }
}

fun View.setLongClick(block: View.() -> Unit) {
    setOnLongClickListener { p0 ->
        block.invoke(p0!!)
        true
    }
}

/**上次点击时间 */
private var lastClickTime: Long = 0

/** 默认时间内（1秒），是否是重复点击*/
fun isFastClick(): Boolean {
    return isFastClick(CLICK_INTERVAL_TIME)
}

/** 规定时间内，是否是重复点击*/
fun isFastClick(millis: Long): Boolean {
    var flag = false
    val curClickTime = System.currentTimeMillis()
    if (curClickTime - lastClickTime >= millis) {
        flag = true
    }
    lastClickTime = curClickTime
    return flag
}
/** 自定义点击监听，适配java*/
abstract class OnMultiClickListener(var millis: Long = CLICK_INTERVAL_TIME) : View.OnClickListener {
    override fun onClick(v: View) {
        if (isFastClick(millis)) {
            onMultiClick(v)
        }
    }
    abstract fun onMultiClick(v: View)
}